package tcp_proxy_middleware

import (
	"fmt"
	"log"

	"gin-gateway/core/dao"
	"gin-gateway/reverse_proxy"
)

func TCPReverseProxyMiddleware() reverse_proxy.TcpHandlerFunc {
	return func(c *reverse_proxy.TcpSliceRouterContext) {
		serviceDetail := GetServiceDetail(c)

		addr := fmt.Sprintf(":%d", serviceDetail.TCPRule.Port)
		lb, err := dao.LoadBalancerManager.GetLoadBalancer(serviceDetail)
		if err != nil {
			_, err = c.Conn.Write([]byte("Get LoadBalancer error:" + err.Error()))
			if err != nil {
				log.Println("TCPReverseProxyMiddleware Conn Write error", err)
				return
			}
			log.Fatalf("[ERROR] GetTcpLoadBalancer %v err:%v\n", addr, err)
			return
		}

		proxy := reverse_proxy.NewTcpLoadBalanceReverseProxy(c, lb)
		proxy.ServeTCP(c.Ctx, c.Conn)
		c.Abort()
	}
}
